﻿CREATE PROCEDURE [dbo].[CashRegistersUpdate]
(
	@Name varchar(50),
	@KKMNumber varchar(20),
	@NextDocNumber int,
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50),
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
 
SET NOCOUNT ON

IF (@NextDocNumber Is Null) OR (@Name Is Null) OR (@KKMNumber Is Null) OR (@Original_Id Is Null) OR (@Original_MD Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF (ltrim(@Name) = '') OR (ltrim(@KKMNumber) = '')
BEGIN
	SELECT @intErrCode = 2, @strMsg = 'Незаполнено наименование или номер!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SELECT @intRet = Id
FROM [CD].[CashRegisters] WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
	SET NOCOUNT OFF;
UPDATE [CD].[CashRegisters] SET [Name] = @Name, [KKMNumber] = @KKMNumber, 
--NextDocNumber = @NextDocNumber,
[Note] = @Note, [MD] = @MD, [MW] = @MW 
WHERE Id = @Original_Id AND MD = @Original_MD;
	
SELECT Id, DepartmentId, Name, KKMNumber, Note, MD, MW 
FROM CD.CashRegisters WHERE (Id = @Original_Id)

RETURN 0
